#include "system_manager.hpp"
#include <iostream>

bool SystemManager::init() {
    try {
        if (!udp_->init()) {
            throw std::runtime_error("UDP initialization failed");
        }
        if (!inference_->init()) {
            throw std::runtime_error("Inference initialization failed");
        }
        return true;
    } catch (const std::exception& e) {
        std::cerr << "Initialization error: " << e.what() << std::endl;
        return false;
    }
}

void SystemManager::start() {
    running_ = true;
    
    // 启动所有工作线程
    threads_.emplace_back(&SystemManager::receiver_thread, this);
    threads_.emplace_back(&SystemManager::inference_thread, this);
    threads_.emplace_back(&SystemManager::monitor_thread, this);
}

void SystemManager::stop() {
    running_ = false;
    
    // 等待所有线程结束
    for (auto& thread : threads_) {
        if (thread.joinable()) {
            thread.join();
        }
    }
    threads_.clear();
}

void SystemManager::receiver_thread() {
    while (running_) {
        cv::Mat received_image;
        if (udp_->receive_image(received_image)) {
            buffer_->write(received_image);
        }
    }
}

void SystemManager::inference_thread() {
    while (running_) {
        cv::Mat frame;
        if (buffer_->read(frame)) {
            std::string direction = inference_->process(frame);
            udp_->send_result(direction);
        }
    }
}

void SystemManager::monitor_thread() {
    while (running_) {
        auto metrics = buffer_->get_metrics();
        std::cout << "Write FPS: " << metrics.write_fps 
                 << ", Read FPS: " << metrics.read_fps 
                 << ", Dropped frames: " << metrics.dropped_frames 
                 << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
} 